package handler

import (
	"github.com/gin-gonic/gin"
	"pic-text-manager/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	data := models.PicText{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offest := (page - 1) * size
	var PicText []models.PicText
	err := models.DB.Debug().Offset(offest).Limit(size).Find(&PicText).Error
	var count int64
	models.DB.Model(&models.PicText{}).Count(&count)
	if err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "展示失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code":  200,
			"msg":   "展示成功",
			"data":  PicText,
			"count": count,
		})
	}
}
